package com.ruoyi.nettyMqttServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: mqtt
 * @Date: 2023-07-14 13:37
 * @author: Fox0g
 * @description: TODO
 */
@Component
public class BootNettyMqttServer {

    @Autowired
    private BootNettyMqttChannelInboundHandler bootNettyMqttChannelInboundHandler;

    /**
     * 	启动服务
     */
    public void startup(int port) throws InterruptedException{
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();

        try {
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 使消息立即发出去，不用等待到一定的数据量才发出去
                    .option(ChannelOption.TCP_NODELAY, true)
                    // 保持长连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.SO_RCVBUF, 10485760)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            /*服务端初始化，客户端与服务器端连接一旦创建，这个类中方法就会被回调，设置出站编码器和入站解码器*/
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            // 设置读写空闲超时时间
                            //channelPipeline.addLast(new IdleStateHandler(600, 600, 1200));
                            channelPipeline.addLast("encoder", new MqttEncoder());
                            channelPipeline.addLast("decoder", new MqttDecoder());
                            channelPipeline.addLast(bootNettyMqttChannelInboundHandler);
//                            channelPipeline.addLast(new BootNettyMqttChannelInboundHandler());
                        }
                    });
            // 绑定端口，同步等待成功
            ChannelFuture f = bootstrap.bind(port).sync();
            if (f.isSuccess()) {
                System.out.println("Netty Start successful, port = " + port);
            } else {
                System.out.println("Netty Start failed");
            }
            // 等待服务监听端口关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            System.out.println("start exception"+e.toString());
        } finally {
            // 退出，释放线程资源
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }


}
